package alarm.ruiqi.com.alarm_pro.options.alarm;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;

import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListListener;
import com.ab.task.thread.AbTaskQueue;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.AlarmEntity;
import alarm.ruiqi.com.alarm_pro.options.MainActivity;
import alarm.ruiqi.com.alarm_pro.options.alarm.UI.AlarmUIHelper;
import alarm.ruiqi.com.alarm_pro.options.alarm.adapter.AlarmListAdapter;
import alarm.ruiqi.com.alarm_pro.options.alarm.add.AddAlarmActivity;
import alarm.ruiqi.com.alarm_pro.options.base.BaseFragment;
import alarm.ruiqi.com.alarm_pro.service.AlarmServiceImpl;
import alarm.ruiqi.com.alarm_pro.service.MobileApplication;
import alarm.ruiqi.com.alarm_pro.utils.Constant;


public class AlarmInfoFragment extends BaseFragment implements View.OnClickListener, MainActivity.MainActivityInterInteractionListener {


    private View mContentView;
    private FloatingActionButton mAddButton;
    private FloatingActionMenu mOperateMenu;
    private ListView mListView;

    private List<AlarmEntity> mAlarmEntities = new ArrayList<>();
    private AlarmListAdapter mAdapter;
    private DbUtils mDbUtils;
    private AbTaskItem queryAlarmItem = new AbTaskItem();
    AbTaskQueue queue = AbTaskQueue.newInstance();
    private AlarmServiceImpl mAlarmervice;
    private MainActivity mainActivity;

    public AlarmInfoFragment() {
    }

    //===================== 生命周期方法  start============================
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("onCreate");
        setUseProgressFragment(true);
        mainActivity = ((MainActivity) MobileApplication.getInstance().getCtx(MainActivity.class.getSimpleName()));
        mainActivity.setMainActivityInterInteractionListener(this);
        mainActivity.getHeadFragment().togglrRightDrawable(false);
        mDbUtils = MobileApplication.getInstance().getDefaultDbutils();
        queryAlarmItem.setListener(new MyrefreshListener());
        mAlarmervice = new AlarmServiceImpl(getActivity());
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        LogUtils.i("onAttach");
    }



    @Override
    public void onResume() {
        super.onResume();
        setUseProgressFragment(true);
        if (mAddButton.isShown() && !((MainActivity) MobileApplication.getInstance().getCtx(MainActivity.class.getSimpleName())).getmDrawerLayout().isDrawerOpen(GravityCompat.START)) {
            //加载动画
            YoYo.with(Techniques.BounceInDown).playOn(mAddButton);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mainActivity.addMenu();
        mainActivity.getHeadFragment().removeRightView();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LogUtils.i("__ onCreateView __");
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    //===================== 生命周期方法 end============================



    @Override
    protected View setAbContentView(LayoutInflater inflater, ViewGroup container) {

        mContentView = inflater.inflate(R.layout.fragment_alarm_info, container, false);
        mListView = (ListView) mContentView.findViewById(R.id.alarm_info_list_alarm);
        // initHead(contentView);
        initView(mContentView);
        LogUtils.i(" setAbContentView ");
        mAdapter = new AlarmListAdapter(getActivity(), mAlarmEntities);
        mListView.setAdapter(mAdapter);
        mListView.setLongClickable(true);
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlarmUIHelper.getInstance().showEditLayout(mAdapter.getCheckState().get(0)[0] == CheckBox.GONE, mainActivity, mAdapter, mAddButton, mOperateMenu);
                return true;
            }
        });
        mListView.setOnScrollListener(new AddButtonControlListener(mAddButton));
        queryAlarm();
        return mContentView;
    }



    public void  startActionForResult(AlarmEntity entity){
        Intent intent = new Intent(getActivity(),AddAlarmActivity.class);
        intent.putExtra(Constant.GENERAL_SAVE_KEY,entity);
        startActivityForResult(intent, 0x1);
    }

    private void queryAlarm() {
        queue.execute(queryAlarmItem);
    }


    private void initView(View parent) {
        mAddButton = (FloatingActionButton) parent.findViewById(R.id.alarm_info_add);
        mAddButton.setKeepScreenOn(true);
        mAddButton.setOnClickListener(this);
        parent.findViewById(R.id.alarm_info_delete_selected).setOnClickListener(this);
        parent.findViewById(R.id.alarm_info_cancel).setOnClickListener(this);
        mOperateMenu = (FloatingActionMenu) parent.findViewById(R.id.alarm_info_operate);
    }




    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.alarm_info_add:
                //添加闹钟
                startActivityForResult(new Intent(getActivity(), AddAlarmActivity.class), 0X1);
                break;
            case R.id.alarm_info_delete_selected:
                //删除闹钟
                mOperateMenu.close(true);
                LogUtils.i("alarm_info_delete_selected");
                for (Integer i : mAdapter.getSelected()){

                }
                List<AlarmEntity> ens = null;
                try {
                    ens = mDbUtils.findAll(Selector.from(AlarmEntity.class).where("id","in",mAdapter.getSelected().toArray()));
                    mAlarmervice.cancelAndeleteAlarms(mDbUtils, ens);
                    mAdapter.clearSelect();

                    LogUtils.i("删除成功>>>>>>");
                } catch (DbException e) {
                    e.printStackTrace();
                    LogUtils.i("删除失败>>>>>>");
                }
                queryAlarm();

                break;
            case R.id.alarm_info_cancel:
                //取消编辑
                LogUtils.i("alarm_info_cancel");
                AlarmUIHelper.getInstance().showEditLayout(false, mainActivity,mAdapter,mAddButton,mOperateMenu);

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.i("requestCode = " + requestCode + " ;resultCode =  " + resultCode + " ; ");
        if (requestCode == 0x1) {
                queryAlarm();
        }
    }

    @Override
    public void onDrawerSlide(float slideOffset) {
        ViewHelper.setTranslationX(mAddButton, slideOffset);
    }

    /**
     * 更新界面:是否有闹钟
     *
     * @param b
     */
    private void updateAlarmInfo(boolean b) {
        mListView.setVisibility(b ? View.VISIBLE : View.GONE);
        mContentView.findViewById(R.id.alarm_info_no_alarm).setVisibility(b ? View.GONE : View.VISIBLE);
    }




    //=========================  查询数据完毕 回调  ===================================================

    class MyrefreshListener extends AbTaskListListener{

        @Override
        public List<?> getList() {
            mAlarmEntities.clear();
            try {
                return  mAlarmervice.checkNextAlarms(mDbUtils.findAll(AlarmEntity.class), System.currentTimeMillis()) ;
            } catch (DbException e) {
                return null;
            }
        }

        @Override
        public void update(List<?> paramList) {
            if (paramList!=null ){
                mAlarmEntities.addAll((Collection<? extends AlarmEntity>) paramList);
            }
            LogUtils.i("paramList.size() = " + mAlarmEntities.size());
            mAdapter.notifyDataSetChanged();
            updateAlarmInfo(mAlarmEntities.size() > 0);
            showContent(mContentView);//展示正文内容
            if ( mOperateMenu.isShown() && mAdapter.getCount()==0){
                mAddButton.setVisibility(View.VISIBLE);
                AlarmUIHelper.getInstance().showEditLayout(false, mainActivity,mAdapter,mAddButton,mOperateMenu);
            }
        }
    }
    //======================== 控制 addButton的监听  =============================================

    public class AddButtonControlListener implements AbsListView.OnScrollListener{

        private  FloatingActionButton addButton;
        private int firstVisibleItem ,visibleItemCount ,totalItemCount;
        private boolean addButtonFlag;
        int[] pos ;


        public AddButtonControlListener(FloatingActionButton button){
            this.addButton = button;
            addButtonFlag =false;

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            this. firstVisibleItem = firstVisibleItem;
            this.visibleItemCount =visibleItemCount;
            this.totalItemCount = totalItemCount;
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if ( scrollState == SCROLL_STATE_IDLE ){
                View childAt = view.getChildAt(visibleItemCount-1);
                int[] location = new int[2]; //最后一项item的y轴值
                childAt.getLocationInWindow(location);
                 //button 的y轴值
                if (pos==null && addButton.isShown() ){
                    pos =new int[2];
                    addButton.getLocationInWindow(pos);
                }
                boolean flag =  pos[1] >= location[1] && pos[1]+addButton.getMeasuredHeight()<=location[1]+childAt.getMeasuredHeight();
                if( totalItemCount>3 && visibleItemCount+firstVisibleItem==totalItemCount){
                    if ( flag &&! mOperateMenu.isShown() && addButton.isShown()&& !addButtonFlag){
                        YoYo.with(Techniques.SlideOutDown).withListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                addButton.setVisibility(View.GONE);
                            }
                        }).playOn(addButton);
                        addButtonFlag = true;
                        return;
                    }
                }
                if(!flag &&addButtonFlag && !addButton.isShown() && !mOperateMenu.isShown()){
                    YoYo.with(Techniques.SlideInUp).withListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationStart(Animator animation) {
                            super.onAnimationStart(animation);
                            addButton.setVisibility(View.VISIBLE);
                        }
                    }).playOn(addButton);
                    addButtonFlag =false;

                }

            }

        }
    }

    //=================== getter setter =================================


    public FloatingActionButton getAddButton() {
        return mAddButton;
    }
}
